import loginByPhone from '../components/controller/loginByPhone.vue'
import home1 from '../components/index/home1.vue'
import home from '../components/index/home.vue'
import loginByAccount from '../components/controller/loginByAccount.vue'
import login from '../components/controller/login.vue'
import register from '../components/controller/register1.vue'
import selectArea from "../components/index/selectArea.vue"
import house from "../components/house/house.vue"
import myself from "../components/myself/myself.vue"
import collectionHouse from '../components/myself/children/collections.vue'
import history from '../components/myself/children/history.vue'
import profile from '../components/myself/children/profile.vue'
import verify from '../components/myself/children/verify.vue'
import posts from '../components/myself/children/posts.vue'
import chat from '../components/chat/ChatOne.vue'
import release from "../components/landlord/release.vue"
import test from "../test/test.vue"
import seetimeHouse from "../components/house/SeetimeHouse.vue"
import booking from "../components/myself/children/booking.vue"
import contract from "../components/house/contract.vue"
import quickSelect from "../components/index/selectQuick.vue"
import recording from "../components/myself/children/recording.vue"
import help from "../components/index/help.vue"
import {
    createRouter,
    createWebHashHistory
} from 'vue-router'
import { message } from "ant-design-vue";

let router = createRouter({
    history: createWebHashHistory(),
    routes: [
        { path: "/", redirect: "/home" },
        {
            path: "/home",
            component: home,
            children: [{
                    path: "home1",
                    component: home1
                },
                {
                    path: "help",
                    component: help
                },
                {
                    path: "quickSelect",
                    component: quickSelect
                },
                {
                    path: "myself",
                    component: myself,
                    children: [{
                            path: "collections",
                            component: collectionHouse
                        },
                        {
                            path: "history",
                            component: history
                        },
                        {
                            path: "profile",
                            component: profile
                        },
                        {
                            path: "verify",
                            component: verify
                        },
                        {
                            path: "posts",
                            component: posts
                        },
                        {
                            path: "booking",
                            component: booking
                        },
                        {
                            path: "recording",
                            component: recording
                        }

                    ]
                },
                {
                    path: "/landlord",
                    component: release
                },
            ]
        },
        {
            path: "/selectArea",
            component: selectArea
        },
        {
            path: "/house",
            component: house
        },

        {
            path: "/user",
            children: [{
                path: "login",
                component: login,
                children: [{
                        path: "loginByPhone",
                        component: loginByPhone,
                    },
                    {
                        path: "loginByAccount",
                        component: loginByAccount,
                    },
                ]
            }, ]
        },
        {
            path: "/user/register",
            component: register,
        },
        {
            path: "/chat",
            component: chat
        },
        {
            path: "/test",
            component: test
        },
        {
            path: "/seetimeHouse",
            component: seetimeHouse
        },
        {
            path: "/contract",
            component: contract
        }
    ]
})

// 定义白名单路由
const whiteList = [
    '/home/home1', // 首页
    '/home', // 首页父路由
    '/user/login', // 登录页
    '/user/login/loginByPhone', // 手机登录
    '/user/login/loginByAccount', // 账号登录
    '/user/register', // 注册页
    '/selectArea' // 区域选择
];

// 添加 JWT 解析函数
function parseJWT(token) {
    if (!token) return {};

    try {
        // 获取 token 的主体部分（第二部分）
        const base64Url = token.split('.')[1];
        const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
        // 解码 JWT payload
        return JSON.parse(window.atob(base64));
    } catch (error) {
        console.error('解析 token 失败:', error);
        return {};
    }
}

// token 过期检查函数
function isTokenExpired(token) {
    const payload = parseJWT(token);
    const currentTime = Math.floor(Date.now() / 1000); // 当前时间（秒）
    return payload.exp && payload.exp < currentTime; // 判断是否过期
}

router.beforeEach(async(to, from, next) => {
    const token = localStorage.getItem("access-token");

    // 检查是否是白名单路径或其子路径
    const isWhitePath = whiteList.some(path => to.path.startsWith(path));

    if (token && isTokenExpired(token)) {
        // token过期时，清除token
        localStorage.removeItem("access-token");
        message.warning("登录已过期，请重新登录");
        localStorage.setItem("access-token", null);
        next();
        return;
    } else if (!token && !isWhitePath) {
        message.warning("请先登录");
        // 使用 replace 替代 next，避免浏览器历史堆积
        await router.replace('/user/login');
        return;
    } else {
        next();
    }
});

export default router